package com.king.juc.n8.threadpooldemo.forkjoindemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RecursiveTask;

/**
 * 1~n 之间整数的和
 *
 * @author king
 * @date 2020/12/12 20:39
 */
@Slf4j(topic = "c.MyTask")
public class MyTask2 extends RecursiveTask<Integer> {
    private int begin;
    private int end;

    public MyTask2(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    public String toString() {
        return "MyTask2{" +
                "begin=" + begin +
                ", end=" + end +
                '}';
    }

    @Override
    protected Integer compute() {
        if (begin == end) {
            log.debug("join() {}", begin);
            return begin;
        }

        if (end - begin == 1) {
            log.debug("join() {} + {} = {}", begin, end, end + begin);
            return begin + end;
        }

        int mid = (end + begin) / 2;

        MyTask2 t1 = new MyTask2(begin, mid);
        t1.fork();
        MyTask2 t2 = new MyTask2(mid + 1, end);
        t2.fork();

        int result = t1.join() + t2.join();
        log.debug("fork() {} + {} = {}", t1, t2, result);
        return result;
    }
}
